package com.zd.kids.ui.activity;

import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.hyy.libray.common.BaseUtils;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.activity.BaseActivity;
import com.shuyu.gsyvideoplayer.GSYVideoADManager;
import com.shuyu.gsyvideoplayer.listener.GSYMediaPlayerListener;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack;
import com.zd.kids.DataBean.BaseDataBean;
import com.zd.kids.DataBean.RecodVideoDataBean;
import com.zd.kids.DataBean.TestTrainWordResultDataBean;
import com.zd.kids.R;
import com.zd.kids.common.Constants;
import com.zd.kids.common.GlideUtil;
import com.zd.kids.common.ToastUtils;
import com.zd.kids.net.CustomApi;
import com.zd.kids.net.CustomObserver;
import com.zd.kids.net.HttpMethod;
import com.zd.kids.ui.view.MyVideoPlayer;
import com.zd.kids.ui.view.WaveView;
import com.zlw.main.recorderlib.RecordManager;
import com.zlw.main.recorderlib.recorder.listener.RecordDataListener;
import com.zlw.main.recorderlib.recorder.listener.RecordResultListener;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class VideoRecordActivity extends BaseActivity {

    String playLink = "http://fancy-sc.oss-cn-hangzhou.aliyuncs.com/dubbing_resource/video/1503581862512_mdjsjdqe-wmzskb_BGM-000536-000548.mp4";


    @BindView(R.id.vedio_play)
    MyVideoPlayer vedioPlay;
    @BindView(R.id.img_answer_left)
    ImageView imgAnswerLeft;
    @BindView(R.id.img_answer_right)
    ImageView imgAnswerRight;

    @BindView(R.id.rl_img_answer_left)
    RelativeLayout rlImgAnswerLeft;
    @BindView(R.id.rl_img_answer_right)
    RelativeLayout rlImgAnswerRight;

    @BindView(R.id.ll_select_answer)
    LinearLayout llSelectAnswer;

    @BindView(R.id.rl_recorder_answer)
    RelativeLayout rlRecorderAnswer;

    @BindView(R.id.progress_bar_answer)
    ProgressBar progressBarAnswer;

    @BindView(R.id.tv_score_detail)
    TextView tvScoreDetail;
    @BindView(R.id.img_answer_result)
    ImageView imgAnswerResult;
    @BindView(R.id.tv_question)
    TextView tvQuestion;

    @BindView(R.id.rl_quesiont_content)
    RelativeLayout rlQuesiontContent;

    @BindView(R.id.rl_quesiont_show)
    RelativeLayout rlQuesiontShow;

    @BindView(R.id.img_record)
    ImageView imgRecorder;
    @BindView(R.id.wave_view_left)
    WaveView waveViewLeft;
    @BindView(R.id.progress_bar_downfile)
    ProgressBar progressBarDownfile;
    @BindView(R.id.tv_down_progress)
    TextView tvDownProgress;
    @BindView(R.id.ll_progress)
    LinearLayout llProgress;
    @BindView(R.id.rl_end)
    LinearLayout rlEnd;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_down_tips)
    TextView tvDownTips;

    private RecordManager recordManager;

    private List<RecodVideoDataBean.ResultBean> queResults;


    private RecodVideoDataBean.ResultBean mCurQuestion;

    /**
     * 获取布局文件地址
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_video_record;
    }

    /***
     * 用户指导的视频
     */
    private String mVideoPath;

    /**
     * 初始化布局
     */
    @Override

    public void initView() {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imgBack.getLayoutParams();
        layoutParams.leftMargin = ImmersionBar.getActionBarHeight(this);
        imgBack.setLayoutParams(layoutParams);

        mVideoPath = getIntent().getStringExtra("VIDEO_PATH");

        mUnitId = getIntent().getStringExtra(TrainTypeListActivity.UNIT_ID_KEY);

        ImmersionBar.with(this)
                .fullScreen(true)
                .hideBar(BarHide.FLAG_HIDE_BAR)
                .init();
        Observable.timer(500, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        ImmersionBar.with(VideoRecordActivity.this).hideBar(BarHide.FLAG_HIDE_BAR)
                                .init();
                    }
                });

        initVideo();
    }


    @Override
    protected void onPause() {
        super.onPause();

        vedioPlay.onVideoPause();
    }

    @Override
    public void initData() {
        super.initData();


        if (!TextUtils.isEmpty(mVideoPath)) {
//            downFiles(mVideoPath);
            vedioPlay.getStartButton().setVisibility(View.VISIBLE);
            vedioPlay.setUp(mVideoPath, true, "");
            vedioPlay.startPlayLogic();
        } else {
            getRecodVideo();
            recordManager = RecordManager.getInstance();

            recordManager.setRecordDataListener(data -> waveViewLeft.addData(data));

            recordManager.setRecordResultListener(result -> updataVidoRecordFile(result.getAbsolutePath()));

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        vedioPlay.onVideoPause();
        vedioPlay.release();
        vedioPlay = null;
    }

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    @Override
    protected IBasePresenter onBasePresenter() {
        return null;
    }


    private String mUnitId;


    private void initVideo() {
        vedioPlay.getFullscreenButton().setVisibility(View.GONE);
        vedioPlay.getBackButton().setVisibility(View.GONE);
        vedioPlay.setRotateWithSystem(false);
        vedioPlay.setIsTouchWiget(false);
        // 如果单独使用请设置setIfCurrentIsFullscreen为true
        vedioPlay.setIfCurrentIsFullscreen(true);
        vedioPlay.setNeedLockFull(true);

        vedioPlay.getStartButton().setVisibility(View.GONE);
//        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_18_9);

        vedioPlay.setVideoAllCallBack(new VideoAllCallBack() {
            @Override
            public void onStartPrepared(String url, Object... objects) {

            }

            @Override
            public void onPrepared(String url, Object... objects) {

            }

            @Override
            public void onClickStartIcon(String url, Object... objects) {

            }

            @Override
            public void onClickStartError(String url, Object... objects) {

            }

            @Override
            public void onClickStop(String url, Object... objects) {
            }

            @Override
            public void onClickStopFullscreen(String url, Object... objects) {

            }

            @Override
            public void onClickResume(String url, Object... objects) {

            }

            @Override
            public void onClickResumeFullscreen(String url, Object... objects) {

            }

            @Override
            public void onClickSeekbar(String url, Object... objects) {

            }

            @Override
            public void onClickSeekbarFullscreen(String url, Object... objects) {

            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                if (TextUtils.isEmpty(mVideoPath)) {

                    rlEnd.setVisibility(View.VISIBLE);
                    completeTrainWord();
                }

            }

            @Override
            public void onEnterFullscreen(String url, Object... objects) {

            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {

            }

            @Override
            public void onQuitSmallWidget(String url, Object... objects) {

            }

            @Override
            public void onEnterSmallWidget(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekVolume(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekPosition(String url, Object... objects) {

            }

            @Override
            public void onTouchScreenSeekLight(String url, Object... objects) {

            }

            @Override
            public void onPlayError(String url, Object... objects) {

            }

            @Override
            public void onClickStartThumb(String url, Object... objects) {

            }

            @Override
            public void onClickBlank(String url, Object... objects) {

            }

            @Override
            public void onClickBlankFullscreen(String url, Object... objects) {

            }
        });
        vedioPlay.setGSYVideoProgressListener(new GSYVideoProgressListener() {
            @Override
            public void onProgress(int progress, int secProgress, int currentPosition, int duration) {

                int curTime = currentPosition / 1000;

                showQueProcessor(curTime);

            }
        });
    }

    private void getRecodVideo() {
        showLoading();
        HttpMethod.getIntence().getRecodVideo(mUnitId, new CustomObserver<RecodVideoDataBean>(this) {
            @Override
            public void onSuccess(RecodVideoDataBean recodVideoDataBean) {
                disLoading();
                queResults = recodVideoDataBean.getResult();
                String videoPath = recodVideoDataBean.getVideo_path();
                if (!TextUtils.isEmpty(videoPath)) {
                    downFiles(videoPath);
                } else {
                    ToastUtils.getIntence().makeTextShow(getString(R.string.data_error_tips));
                }


            }

            @Override
            public void onError(String errorCode) {
                ToastUtils.getIntence().makeTextShow(getString(R.string.data_error_tips));
                finish();
            }
        });
    }


    private void showQueProcessor(int curTime) {
        if (queResults == null) {
            return;
        }
        for (RecodVideoDataBean.ResultBean resultBean : queResults) {
            if (resultBean.getTime() == curTime) {
                if (isAnswerQuetioning) {
                    return;
                }
                mCurQuestion = resultBean;
                showSelectQuestion();
                return;
            }
        }
    }

    private int isCurSelectAnswer;

    @OnClick({R.id.img_answer_left, R.id.rl_end, R.id.img_leave, R.id.img_restart, R.id.img_back, R.id.rl_quesiont_show, R.id.img_answer_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_end:
            case R.id.rl_quesiont_show:
                break;
            case R.id.img_answer_left:
                isCurSelectAnswer = 1;
                rlImgAnswerLeft.setBackgroundResource(R.drawable.shape_video_select_ques_bg_select);
                rlImgAnswerRight.setBackgroundResource(R.drawable.shape_video_select_ques_bg_default);
                break;
            case R.id.img_answer_right:
                isCurSelectAnswer = 2;
                rlImgAnswerRight.setBackgroundResource(R.drawable.shape_video_select_ques_bg_select);
                rlImgAnswerLeft.setBackgroundResource(R.drawable.shape_video_select_ques_bg_default);
                break;
            case R.id.img_leave:
            case R.id.img_back:
                rlEnd.setVisibility(View.GONE);
                finish();
                break;

            case R.id.img_restart:
                rlEnd.setVisibility(View.GONE);
                vedioPlay.startPlayLogic();
                break;

        }
    }


    private void showSelectQuestion() {
        if (mCurQuestion != null) {
            countDownSelectQuestion();
        }
    }

    private void preparQuestion(boolean isSelecQues) {
        Observable
                .timer(1500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        isAnswerQuetioning = true;
                        vedioPlay.lockTouch();
                        rlQuesiontShow.setVisibility(View.VISIBLE);
                        rlQuesiontContent.setVisibility(View.VISIBLE);
                        imgAnswerResult.setVisibility(View.GONE);
                        tvQuestion.setText(mCurQuestion.getWord());

                        rlRecorderAnswer.setVisibility(View.GONE);
                        llSelectAnswer.setVisibility(View.GONE);

                        if (isSelecQues) {
                            llSelectAnswer.setVisibility(View.VISIBLE);

                            isCurSelectAnswer = 0;

                            rlImgAnswerLeft.setBackgroundResource(R.drawable.shape_video_select_ques_bg_default);
                            rlImgAnswerRight.setBackgroundResource(R.drawable.shape_video_select_ques_bg_default);

                            imgAnswerLeft.setEnabled(false);
                            imgAnswerRight.setEnabled(false);

                            GlideUtil.load(mCurQuestion.getOption_1(), imgAnswerLeft);
                            GlideUtil.load(mCurQuestion.getOption_2(), imgAnswerRight);

                        } else {
                            rlRecorderAnswer.setVisibility(View.VISIBLE);
                            waveViewLeft.setVisibility(View.GONE);

                            imgRecorder.setImageResource(R.mipmap.ic_recoder_ques_default);
                            imgRecorder.setEnabled(false);
                        }
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        answerQuestion(isSelecQues);
                    }
                });
    }

    private void answerQuestion(boolean isSelecQues) {
        Observable
                .interval(100, TimeUnit.MILLISECONDS)
                .take(isSelecQues ? 50 : 35)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        progressBarAnswer.setProgress(100);
                        if (isSelecQues) {

                            imgAnswerLeft.setEnabled(true);
                            imgAnswerRight.setEnabled(true);

                        } else {
                            waveViewLeft.setVisibility(View.VISIBLE);

                            imgRecorder.setEnabled(true);
                            imgRecorder.setImageResource(R.mipmap.ic_recoder_ques_recording);


                            recordManager.start(mCurQuestion.getWord() + "_" + mCurQuestion.getPinyin() + mCurQuestion.getId() + "_video_recorde");
                        }

                    }

                    @Override
                    public void onNext(Long aLong) {

                        float scale = (float) 100 / (float) (isSelecQues ? 50 : 35) * (aLong + 1);
                        LogUtils.i("progressBarAnswer", aLong + "scale:" + scale);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            progressBarAnswer.setProgress((int) (100 - scale), true);
                        } else {
                            progressBarAnswer.setProgress((int) (100 - scale));
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        if (isSelecQues) {
                            showAnsResult(mCurQuestion.getAnswer() == isCurSelectAnswer ? 1 : 3);
                        } else {
                            waveViewLeft.setVisibility(View.GONE);

                            imgRecorder.setImageResource(R.mipmap.ic_recoder_ques_default);
                            recordManager.stop();
                        }

                    }
                });

    }

    private boolean isAnswerQuetioning;


    private void countDownSelectQuestion() {
        preparQuestion(mCurQuestion.getTypeid() == 2);
    }


    /**
     * 下载视频资源
     *
     * @param urlPath
     */
    private void downFiles(String urlPath) {
        int index = urlPath.lastIndexOf("/");
        String fileName = urlPath.substring(index == -1 ? 0 : index);

        if (FileUtils.isFile(Constants.VIDEO_ROOT_PATH + fileName)) {
            startPlayVideo(Constants.VIDEO_ROOT_PATH + fileName);
        } else {

            String downFileName = Constants.VIDEO_ROOT_PATH + fileName;

            String downFileTempName = Constants.VIDEO_ROOT_PATH + "/TEMP/" + fileName;

            FileUtils.createFileByDeleteOldFile(downFileTempName);

            HttpMethod.getIntence().downFile(urlPath, new File(downFileTempName), new Observer<Integer>() {
                @Override
                public void onSubscribe(Disposable d) {
                    llProgress.setVisibility(View.VISIBLE);
                }

                @Override
                public void onNext(Integer integer) {

                    Log.i("HttpMethod", "onNext:" + integer);

                    progressBarDownfile.setProgress(integer);
                    tvDownProgress.setText(integer + "%");
                }

                @Override
                public void onError(Throwable e) {
                    llProgress.setVisibility(View.GONE);
                    ToastUtils.getIntence().makeTextShow(getString(R.string.data_error_tips));
                    finish();
                }

                @Override
                public void onComplete() {
                    llProgress.setVisibility(View.GONE);

                    boolean isMoved = FileUtils.move(downFileTempName, downFileName);

                    startPlayVideo(downFileName);
                }
            });
        }

    }


    private void startPlayVideo(String filePath) {
        if (!TextUtils.isEmpty(filePath) && FileUtils.isFileExists(filePath)) {
            vedioPlay.getStartButton().setVisibility(View.VISIBLE);
            vedioPlay.setUp(filePath, true, "");
            vedioPlay.startPlayLogic();

        } else {
            ToastUtils.getIntence().makeTextShow(StringUtils.getString(R.string.data_error_tips));
        }
    }

    private void updataVidoRecordFile(String filePath) {
        showLoading();
        Observable.just(filePath)
                .flatMap((Function<String, ObservableSource<String>>) s -> {
                    File file = new File(filePath);

                    return Observable.just(BaseUtils.fileToBase64(file));
                })
                .flatMap((Function<String, ObservableSource<BaseDataBean<TestTrainWordResultDataBean>>>) base64 -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("file64", base64);
                    map.put("word", mCurQuestion.getWord());
                    map.put("pinyin", mCurQuestion.getPinyin());
                    CustomApi.isSmalllTimeOut = true;
                    return CustomApi.getIntence().getApi().uploadVideoRecord(map).timeout(1500, TimeUnit.MILLISECONDS);
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseDataBean<TestTrainWordResultDataBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseDataBean<TestTrainWordResultDataBean> resultDataBeanBaseDataBean) {

                        CustomApi.isSmalllTimeOut = false;
                        FileUtils.delete(filePath);
                        disLoading();
                        TestTrainWordResultDataBean item = resultDataBeanBaseDataBean.getData();
                        int totalScore = item.getTotal();
                        tvScoreDetail.setText(String.format(getString(R.string.score_num), totalScore + ""));
                        int level;
                        if (totalScore >= 80) {
                            level = 1;
                        } else if (totalScore >= 60 && totalScore < 80) {
                            level = 2;
                        } else {
                            level = 3;
                        }
                        showAnsResult(level);
                    }

                    @Override
                    public void onError(Throwable e) {
                        CustomApi.isSmalllTimeOut = false;
                        FileUtils.delete(filePath);
                        disLoading();
                        tvScoreDetail.setText("error" + String.format(getString(R.string.score_num), "0"));

                        showAnsResult(3);

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 展示答案结果
     */
    private void showAnsResult(int level) {
        Observable.timer(1500, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        imgAnswerResult.setVisibility(View.VISIBLE);
                        rlQuesiontContent.setVisibility(View.GONE);

                        int gifRes;

                        if (level == 1) {
                            gifRes = R.mipmap.ic_answer_great;
                        } else if (level == 2) {
                            gifRes = R.mipmap.ic_answer_bad;
                        } else {
                            gifRes = R.mipmap.ic_answer_fighting;
                        }

                        Glide.with(VideoRecordActivity.this)
                                .asGif()
                                .load(gifRes)
                                .into(imgAnswerResult);

                        playTipsVoice(level);
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                        tvScoreDetail.setText("");

                        isAnswerQuetioning = false;
                        vedioPlay.unLockTouch();
                        rlQuesiontShow.setVisibility(View.GONE);

                    }
                });
    }


    private void completeTrainWord() {
        HttpMethod.getIntence().setVideoCompleteResult(mUnitId, new CustomObserver<BaseDataBean>(this) {
            @Override
            public void onSuccess(BaseDataBean baseDataBean) {
            }

            @Override
            public void onError(String errorCode) {

            }
        });
    }

    @Override
    public void finish() {
        FileUtils.deleteAllInDir(Constants.RECORD_ROOT_PATH);
        super.finish();
    }

    private void playTipsVoice(int startNum) {

        int voiceRes;

        if (startNum == 1) {
            voiceRes = R.raw.voice_tips_start3;
        } else if (startNum == 2) {
            voiceRes = R.raw.voice_tips_start2;
        } else {
            voiceRes = R.raw.voice_tips_stars1;
        }

        MediaPlayer mMediaPlayer = MediaPlayer.create(this, voiceRes);
        mMediaPlayer.setAudioStreamType(3);
        mMediaPlayer.start();
    }

}
